<template>
  <!-- 登录状态 -->
  <div v-if="logined">
    <!-- 任务大厅 -->
    <div class="task-hall">

      <div class="nav">
          <!-- 顶部导航栏 -->
          <van-nav-bar title="任务大厅" :border="false" />

          <!-- 搜索栏容器 -->
          <div class="search-container">
        <!-- 搜索框 -->
        <van-search
        v-model="searchText"
        placeholder="请输入关键字进行搜索 如冬筑"
        shape="round"
        background="#ffffff"
        :style="{ flex: 1 }"
        />
        <!-- 查询按钮，用于触发搜索功能 -->
        <van-button 
      size="small" 
      type="primary" 
      class="search-button" 
      @click="onSearch"
        >查询</van-button>
          </div>

      <!-- 筛选和排序按钮容器 -->
      <div class="filter-sort-container">
        <!-- 筛选按钮，通过 setActiveFilter 方法切换当前过滤器 -->
         <!-- 全部 -->
        <van-button 
          plain 
          hairline 
          type="primary" 
          size="small" 
          class="filter-button" 
          :class="{ active: activeFilter === '全部' }"
          @click="setActiveFilter('全部')"
        >
          全部
        </van-button>
        <!-- 粤海 -->
        <van-button 
          plain 
          hairline 
          type="primary" 
          size="small" 
          class="filter-button" 
          :class="{ active: activeFilter === '粤海' }"
         @click="setActiveFilter('粤海')"
        >
        粤海
        </van-button>
        <!-- 沧海 -->
        <van-button 
          plain 
          hairline 
          type="primary" 
          size="small" 
          class="filter-button" 
          :class="{ active: activeFilter === '沧海' }"
          @click="setActiveFilter('沧海')"
        >
          沧海
        </van-button>

          <!-- 排序按钮 -->
          <van-button
            size="small"
            type="primary"
            class="sort-button"
            @click="pickerVisible = true"
          >
            <img src="../../assets/images/sort.png" alt="" class="font-class">
          </van-button>

          <!-- 排序选择弹窗 -->
          <van-popup v-model:show="pickerVisible" position="bottom">
            <van-picker
              show-toolbar
              :columns="sortOptions"
              @confirm="onSortChange"
              v-model="selectedSort"
              @cancel="pickerVisible = false"
            />
          </van-popup>
        </div>
        </div>

      <!-- 任务列表 -->
      <van-list
        v-model:loading="loading" 
        :finished="finished" 
        finished-text="被看光了~" 
        @load="onLoad">
        <van-cell-group class="orderList" v-for="task in sortedList" :key="task" inset @click="showOrderDetail(task)">
          <!-- 任务项：商店信息 -->
          <van-cell>
          <template #icon>
            <!-- 头像 -->
            <img :src="task.avatar || defaultAvatar" style="width: 40px;height: 40px;border-radius: 50%;">
          </template>
          <template #value>
            <!-- 备注信息 -->
            <span class="description">{{ '备注:'+task.description }}</span>
            <span class="item">{{ getDisplayItems(task) }}</span>
          </template>
          </van-cell>
          <!-- 任务项：取件地址信息 -->
          <van-cell>
          <template #icon>
            <!-- 取件图标 -->
            <img src="../../assets/images/pickuplogo.png" class="logoStyle">
          </template>
          <template #value>
            <!-- 地址详情 -->
            <span class="addressStyle">{{ task.pickupAddress }}</span>
          </template>
          </van-cell>
          <!-- 任务项：收件地址信息 -->
          <van-cell>
          <template #icon>
            <!-- 收件图标 -->
            <img src="../../assets/images/deliverylogo.png" class="logoStyle">
          </template>
          <template #value>
            <!-- 地址描述 -->
            <span class="addressStyle">{{ task.deliveryAddress }}</span>
          </template>
          <template #right-icon>
            <div class="task-price">
              <!-- 价格信息 -->
              <span class="price">{{ task.reward }}元</span>
              <!-- 订单号及时间信息 -->
              <div class="order-info">
                <span style="margin-right: 15px;">订单号：{{ task.orderId }}</span>
                <span>{{ task.timeAgo }}</span>
              </div>
            </div>
          </template>
          </van-cell>
        </van-cell-group>
      </van-list>
    </div>
  </div>

  <!-- 未登录状态 -->
  <div  class="unlogin" v-else>
    <img src="../../assets/images/未登录-头像.png" alt="">
    <h3>暂未登录</h3>
    <div class="des">快去登录，迫不及待与你相见啦~</div>
    <button @click="gotologin">立即登录</button>
  </div>
  
  <!-- 订单详情弹窗 -->
  <div v-if="showDialog" class="dialog-wrapper">
    <div class="dialog-background" @click="showDialog = false"></div>
    <div class="content-background">
      <h3>订单详情</h3>
      <img src="../../assets/images/OrderDetailback.png" alt="" class="back-person">
      <div class="dialog-content">
      <div class="order-detail">
        <div class="detail-item">
          <div class="orange">
            <div class="label">取件地址：</div>
          </div>
          <span class="value">{{ selectedTask.pickupAddress }}</span>
        </div>
        <div class="detail-item">
          <div class="orange">
            <div class="label">收件地址：</div>
          </div>
          <span class="value">{{ selectedTask.deliveryAddress }}</span>
        </div>
        <div class="detail-item">
          <div class="orange">
            <div class="label">快递信息：</div>
          </div>
          <span class="value">{{ getDisplayItems(selectedTask) }}</span>
        </div>
        <div class="detail-item">
          <div class="orange">
            <div class="label">收费金额：</div>
          </div>
          <span class="value">{{ selectedTask.reward }}元</span>
        </div>
      </div>
      <div class="dialog-footer">
      <button v-if="selectedTask.customerId !== user.userId" @click="showDialog = false">取消</button>
      <button v-if="selectedTask.customerId !== user.userId" @click="handleconfirmOrder">确认领取</button>
      <span v-else class="self-order">这是您自己发布的订单</span>
      </div>
      </div>
    </div>  
  </div>

</template>

<script setup lang="ts">
import { ref,onMounted , watch, computed} from 'vue'; // 引入 ref 以创建响应式变量
import { useRouter } from 'vue-router'; // 引入 Vue Router 用于导航
import { getTask,confirmOrder } from '../../api/Task/index';
import { useTokenStore } from "../../stores/Login";
import defaultAvatar from '../../assets/images/icon.png';
import { showToast } from 'vant';

const loading = ref<boolean>(false) // 是否正在加载数据
const finished = ref<boolean>(false) // 是否已加载完所有数据
const list = ref<Order[]>([]) // 任务列表
const page = ref<number>(1) // 当前页码
const size= ref<number>(10) // 每页数据量
const pickupFilter = ref<string>('') // 取件地址过滤器
const deliveryFilter = ref<string>('') // 送件地址过滤器
const logined = ref<boolean>(false)
const {user} = useTokenStore()
const maxPage = ref<number>(10) // 最大页码
const router = useRouter()
const searchText = ref('') // 搜索框文本
const activeFilter = ref('全部') // 当前筛选器
const showDialog = ref(false);
const selectedTask = ref({});

// 新增响应式变量
const sortOptions = [
  { text: '发布时间', value: '发布时间' },
  { text: '奖励金额', value: '奖励金额' },
];
const sortCriteria = ref<string>('发布时间');
const pickerVisible = ref<boolean>(false);
  const selectedSort = ref<string[]>(['发布时间']); // 修改为数组类型

// 计算排序后的任务列表
const sortedList = computed(() => {
  return [...list.value].sort((a, b) => {
    switch (sortCriteria.value) {
      case '发布时间':
        return new Date(b.timeAgo).getTime() - new Date(a.timeAgo).getTime();
      case '奖励金额':
        return b.reward - a.reward;
      default:
        return 0;
    }
  });
});

// 判断是否登录
onMounted(()=>{
user.token ? logined.value=true : logined.value=false;
  // 加载排序偏好（可选）
  const storedSort = localStorage.getItem('sortCriteria');
  if (storedSort) {
    sortCriteria.value = storedSort;
    selectedSort.value = [storedSort]; // 设置为数组
  }
})

// 初始加载数据
const onLoad = () =>{
  if (page.value > maxPage.value) {
  finished.value = true;
  loading.value = false;
  return;
}

  //异步更新数据
getTask({page:page.value,size:size.value, pickupFilter:pickupFilter.value,deliveryFilter:deliveryFilter.value}).then(res =>{
    if(res.data.code===200){
      page.value++;
      list.value = list.value.concat(res.data.data.orders);
      maxPage.value = res.data.data.totalPages;
     
    }
    
    //加载状态结束
     loading.value = false;

    //数据加载全部完成
    if(res.data.code===500){
      finished.value = true;
    }
  })
}

// 定义任务的数据结构
interface Order {
  orderId: number
  customerId : number
  courierId : number
  timeAgo: string
  description: string
  phoneNum : string
  pickupAddress: string
  deliveryAddress: string
  smallNum : number
  mediumNum : number
  bigNum : number
  reward: number
  avatar: string
}

function getDisplayItems(task: Order): string {
const parts: string[] = [];
if (task.smallNum > 0) {
  parts.push(`${task.smallNum} 件小件`);
}
if (task.mediumNum > 0) {
  parts.push(`${task.mediumNum} 件中件`);
}
if (task.bigNum > 0) {
  parts.push(`${task.bigNum} 件大件`);
}
return parts.join(' ');
}

// 用于改变筛选器的功能
const setActiveFilter = (filter: string) => {
  activeFilter.value = filter;
  if (filter !== '全部') {
   pickupFilter.value = filter; 
  } else{
    pickupFilter.value = '';
  }
  page.value = 1; // 重置页码
  list.value = []; // 清空当前数据
  finished.value = false; // 重置完成状态
  loading.value = true; // 开始加载数据
  onLoad(); // 重新加载数据
}

// 搜索功能
const onSearch = () => {
  deliveryFilter.value = searchText.value; // 只设置 deliveryFilter
  page.value = 1; // 重置页码
  list.value = []; // 清空当前数据
  finished.value = false; // 重置完成状态
  loading.value = true; // 设置加载状态
  onLoad(); // 重新加载数据
};

// 跳转到登录页面
const gotologin =() =>{
  router.push('/login')
}

const showOrderDetail = (task) => {
selectedTask.value = task;
showDialog.value = true;
};

const handleconfirmOrder = async() => {
try{
  const response = await confirmOrder({orderId:selectedTask.value.orderId});
  console.log('订单确认成功:', response.data);
  showToast({ type: 'success', message: '领取成功' });
  showDialog.value = false;
  list.value = list.value.filter(order => order.orderId !== selectedTask.value.orderId);// 从任务列表中移除该订单
}catch (error) {
  console.error('订单确认失败:', error);
  showToast({ type: 'fail', message: '领取失败' });
}
};

// 处理排序变化
const onSortChange = (value: { selectedValues: string[], selectedOptions: any[], selectedIndexes: number[] }) => {
  console.log('onSortChange called with value:', value); // 调试日志
  if (value.selectedValues.length > 0) {
    sortCriteria.value = value.selectedValues[0]; // 更新排序标准
    selectedSort.value = value.selectedValues; // 保持数组类型
    localStorage.setItem('sortCriteria', value.selectedValues[0]); // 保存排序偏好（可选）
    showToast({ type: 'success', message: `排序方式: ${sortCriteria.value}` });
  }
  pickerVisible.value = false; // 关闭弹窗
};

</script>

<style scoped>
.task-hall {
background-color: #f7f8fa; /* 背景颜色 */
min-height: 100vh; /* 最小高度设为视口高度 */
}

.search-container {
padding: 8px 16px; /* 内间距 */
background-color: #ffffff; /* 背景颜色 */
display: flex; /* 采用 flex 布局 */
align-items: center; /* 垂直居中 */
gap: 8px; /* 子元素之间距离 */
}

.search-button {
border-radius: 100px; /* 按钮圆角 */
background-color: #ff6b6b; /* 背景颜色 */
border-color: #ff6b6b; /* 边框颜色 */
flex-shrink: 0; /* 不允许收缩 */
}

/* 筛选和排序按钮容器 */
.filter-sort-container {
  display: flex;
  align-items: center;
  justify-content: space-between; /* 两端对齐 */
  background-color: #ffffff; /* 保证容器背景不变 */
  padding: 8px 16px; /* 保证内间距和之前一致 */
}

/* 排序按钮样式 */
.sort-button {
  background-color: #fff;
  border-color: #fff;
  color: white;
  border-radius: 100px;
  flex-shrink: 0;
}

/*排序按钮图标*/
.font-class{
  width: 25px;
  height: 25px;
}

.filter-buttons {
background-color: #ffffff; /* 背景颜色 */
display: flex; /* flex 布局 */
gap: 8px; /* 按钮之间间距 */
flex: 1; /* 自动填充剩余空间 */
}

.filter-button {
flex: 1; /* 让按钮自动扩展并填充容器 */
padding: 0 20px; /* 增加内边距使按钮更长 */
min-width: 100px; /* 设置按钮的最小宽度 */
border-radius: 100px; /* 按钮圆角 */
font-size: 14px; /* 字体大小 */
border-color: #e8e8e800; /* 边框颜色，透明 */
color: #323233; /* 字体颜色 */
text-align: center;
}

.filter-button.active {
color: #ff6b6b; /* 活动状态文本颜色 */
background-color: #ffefef; /* 背景颜色 */
border-color: #fdfdfd00; /* 边框颜色 */
}


.orderList{
  margin: 10px;
}

.description {
font-weight: bold; /* 字体加粗 */
color: #000;
text-align: left;
display: block;
margin-left: 10px;
}

.item{
  text-align: left;
  display: block;
  margin-left: 20px;
}

.logoStyle{
  width: 20px;
  height: 20px; 
  margin-right: 5px;
}

.addressStyle{
  font-size: 14px;
  font-weight: bold;
  color: #000000;
  text-align: left;
  display: block;
  margin-left: 10px;

}

.task-price {
text-align: right; /* 右对齐 */
}

.van-cell:after {
border-bottom: none !important;
}

.price {
color: #ff6b6b; /* 价格文本颜色 */
font-weight: bold; /* 加粗 */
font-size: 16px; /* 字体大小 */
}

.order-info {
font-size: 12px; /* 文字大小 */
color: #999; /* 字体颜色 */
}

/* Vant 组件的样式自定义 */
:deep(.van-nav-bar__title) {
color: #ff6b6b; /* 标题颜色 */
}

:deep(.van-search__action) {
padding: 0 8px; /* 搜索框动作按钮内边距 */
}

:deep(.van-badge--dot) {
top: 0; /* 上边距 */
right: 0; /* 右边距 */
}

:deep(.van-search) {
padding: 0; /* 搜索框内边距 */
}

.unlogin {
width: 223px;
height: 255px;
position: absolute;
left: 50%;
transform: translateX(-50%);
top: 30%;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
text-align: center;
}

.unlogin img{
width: 125px;
margin-bottom: 15px;
}

.unlogin .des{
font-size: 15px;
color: #6C6C6C;
margin-top: 10px;
margin-bottom: 20px
}

.unlogin button{
width: 129px;
height: 48px;
background-color: rgba(252, 30, 9, 0.8);
color: #FFFFFF;
border: none;
border-radius: 4px;
}

.dialog-wrapper {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
display: flex;
justify-content: center;
align-items: center;
z-index: 1000;
}

.dialog-background {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
background-color: rgba(0, 0, 0, 0.5); /* 半透明黑色背景 */
}

.dialog-content {
position:absolute;
top: 65px;
left: 10px;
background-color: #fff;
padding: 20px;
border-radius: 10px;
z-index: 1001;
width: 80%;
max-width: 400px;
height: 260px;
}

.order-detail {
margin-top: 10px;
}

.detail-item {
display: flex;
justify-content: space-between;
margin-bottom: 20px;
align-items: center;
}


.label {
font-weight: bold;
color: #FFFFFF;
margin-left: 15px;
margin-top: 5px;
}

.value {
width: 128px;
color: #333;
}

.dialog-footer {
display: flex;
margin-top: 20px;
}

.dialog-footer button {
margin-left: 10px;
padding: 10px 20px;
border: none;
border-radius: 5px;
cursor: pointer;
}

.dialog-footer button:first-child {
background-color: #f56c6c;
color: #fff;
}

.dialog-footer button:last-child {
background-color: #409eff;
color: #fff;
margin-left: 50px;
}

.content-background{
position: relative;
width: 300px;
height: 318px;
background-color: #FFBF6B;
border-radius: 40px 16px 16px 16px;
padding-top: 65px;
}

.content-background h3{
color: #D37902;
font-size: 24px;
width: 100px;
position:absolute;
top: 20px;
left: 40px;
}

.back-person{
width: 183px;
height: 119px;
position: absolute;
top: -40px;
left: 160px;
}

.self-order {
color: #f56c6c;
font-weight: bold;
margin-left: 40px;
margin-top: 10px;
}

.orange{
width: 100px;
height: 30px;
background: #FFCB87;
border-radius: 10px;
}


</style>

